Attribute VB_Name = "modHandleData"
Option Explicit

Public Sub HandleData(ByVal index As Long, ByVal data As String)
    Dim parse() As String
    
    parse = Split(data, SEP_CHAR)
    
    'Check Commands
    Select Case LCase$(parse(0))
        Case "createuser"
            Call Packet_CreateUser(index, parse(1), parse(2), parse(4), parse(3))
            Exit Sub
            
        Case "loginuser"
            Call Packet_LoginUser(index, parse(1), parse(2), parse(3))
            Exit Sub
    
        Case "logoutuser"
            Call Packet_LogoutUser(index, parse(1))
            Exit Sub
            
    End Select
End Sub

'Packets
Public Sub Packet_CreateUser(index As Long, username As String, Password As String, Sec_Word As String, Optional IP As String = "127.0.0.1")
    'Checks Length
    If Len(username) < 4 Then
        Call Send_PlainMsg(index, "Username Must Be At Least 4 Characters Long!")
        Exit Sub
    Else
        If Len(Password) < 5 Then
            Call Send_PlainMsg(index, "Password Must Be At Least 5 Characters Long!")
            Exit Sub
        End If
    End If
    
    'Other basic Checks
    If (isIPUsed(IP) = False) Or (frmServer.Socket(0).LocalIP) Then
        If Not UserExists(LCase$(Trim$(username))) Then
            Call RegisterNew(username, Password, Sec_Word, IP)
            Call Send_PlainMsg(index, "User Created Successfully!")
            Call ListReggedPasswords
            Call ListReggedUsernames
        Else
            Call Send_PlainMsg(index, "User Already Exists!")
            Exit Sub
        End If
    Else
        Call Send_PlainMsg(index, "You can only have one user per IP!")
        Exit Sub
    End If
End Sub

Public Sub Packet_LoginUser(ByVal index As Integer, ByVal username As String, ByVal Password As String, ByVal Sec_Word As String)
    Dim i As Integer
    'Checks user password and login and sec_code
    If Not UserExists(LCase$(Trim$(username))) Then
        Call Send_PlainMsg(index, "Username or Password Incorrect!")
        Exit Sub
    Else
        If Not PassCorrect(LCase$(username), Password) Then
            Call Send_PlainMsg(index, "Username or Password Incorrect!")
            Exit Sub
        Else
            If Not SecWordCorrect(LCase$(username), Sec_Word) Then
                Call Send_PlainMsg(index, "Incorrect Security Word!")
                Exit Sub
            End If
        End If
    End If
    
    If isMultiLogin(username) Then
        Exit Sub
    End If
    
    Call LoginPlayer(index, username)
    
    If isLoggedIn(index) Then _
        Call Send_UserAuthenticated(index, username)
        
    Call RefreshLoggedIn
End Sub

'logs user out
Public Sub Packet_LogoutUser(ByVal index As Integer, ByVal username As String)
    Call SavePlayer(index)
    Call Logout(index)
    Call RefreshLoggedIn
    Call Disconnect(index)
End Sub

